package com.example.administrator.shzs.fragment;


import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.example.administrator.shzs.R;
import com.example.administrator.shzs.entity.OrderAll;
import com.example.administrator.shzs.utils.NetWorkUtils;
import com.example.administrator.shzs.utils.ToastUtils;
import com.example.administrator.shzs.parse.ParseUserData;
import com.example.administrator.shzs.activity.LogInActivity;
import com.example.administrator.shzs.app.MyApplication;
import com.example.administrator.shzs.url.Contents;
import com.example.administrator.shzs.entity.User;
import com.example.administrator.shzs.ui.AttentionShopActivity;
import com.example.administrator.shzs.ui.GiftOrderActivity;
import com.example.administrator.shzs.ui.IntegralActivity;
import com.example.administrator.shzs.ui.ModifyLoginPasswordActivity;
import com.example.administrator.shzs.ui.ModifyPayPasswordActivity;
import com.example.administrator.shzs.ui.ShippingAddressActivity;
import com.example.administrator.shzs.ui.SystemSetActivity;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;


/**
 * 我的 Fragment
 */
public class UserFragment extends Fragment implements View.OnClickListener {

    private TextView tvUserName;
    private ImageView User_Setting;
    private CircleImageView User_Image;
    private TextView User_Integral; //我的积分
    private TextView User_Balance; //我的余额
    private LinearLayout User_Order;//礼品订单
    private LinearLayout Uesr_Current_integration;//当前积分
    private LinearLayout Uesr_Modify_login_password;//登录密码
    private LinearLayout Uesr_Pay_attention_to_the_store;//关注店家
    private LinearLayout Uesr_Receipt_address_management;//地址管理
    private LinearLayout Uesr_check_for_updates;//检查更新
    private LinearLayout Uesr_Share;//分享好友
    private TextView User_Call;//电话
    private Button L_Login;//退出登录

    //实体类
    private User userdata;

    private NetWorkUtils netWorkUtils;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user, null);

        netWorkUtils=new NetWorkUtils(getActivity());
        //初始化id
        inidata(view);

        //点击事件
        inidataEven();
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();

        autoLogin();
    }

    /**
     * 自动登录
     */
    private boolean autoLogin() {
        String userNumber = MyApplication.app.getUserNumber();
        String userId = MyApplication.app.getUserId();
        String point = MyApplication.app.getPoint();


        if(netWorkUtils.getNetWorkState()) {//有网

            if (userId != null) {
                //说明已经登录了
                User_Integral.setText(point);
                tvUserName.setText(userNumber);
                User_Balance.setText("0");
                L_Login.setVisibility(View.VISIBLE);
                return true;
            }
        }else {
            ToastUtils.showMessageShort(getActivity(),"请检查网络");
        }
        return false;//没网
    }


    //页面切换到当前界面时处理广播
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        //如果切换当前fragment就去发送一条广播
        if (!hidden){

            //自动登录
            autoLogin();

            if (MyApplication.app.getUserId() == null) {

                inidataFromWeb();

            }
        }
    }

    /**
     * 点击事件
     */
    private void inidataEven() {

        User_Image.setOnClickListener(this);//登陆
        Uesr_Pay_attention_to_the_store.setOnClickListener(this);
        Uesr_Receipt_address_management.setOnClickListener(this);
        Uesr_Share.setOnClickListener(this);
        User_Call.setOnClickListener(this);
        Uesr_Modify_login_password.setOnClickListener(this);
        Uesr_Current_integration.setOnClickListener(this);
        User_Order.setOnClickListener(this);
        User_Setting.setOnClickListener(this);
        L_Login.setOnClickListener(this);


    }

    //初始化id
    private void inidata(View view) {

        tvUserName = (TextView) view.findViewById(R.id.User_Name);
        User_Setting = (ImageView) view.findViewById(R.id.User_Setting);
        User_Image = (CircleImageView) view.findViewById(R.id.User_Image);
        User_Integral = (TextView) view.findViewById(R.id.User_Integral); //我的积分
        User_Balance = (TextView) view.findViewById(R.id.User_Balance); //我的余额
        User_Order = (LinearLayout) view.findViewById(R.id.User_Order);//礼品订单
        Uesr_Current_integration = (LinearLayout) view.findViewById(R.id.Uesr_Current_integration);//当前积分
        Uesr_Modify_login_password = (LinearLayout) view.findViewById(R.id.Uesr_Modify_login_password);//登录密码
        Uesr_Pay_attention_to_the_store = (LinearLayout) view.findViewById(R.id.Uesr_Pay_attention_to_the_store);//关注店家
        Uesr_Receipt_address_management = (LinearLayout) view.findViewById(R.id.Uesr_Receipt_address_management);//地址管理
        Uesr_Share = (LinearLayout) view.findViewById(R.id.Uesr_Share);//分享好友
        User_Call = (TextView) view.findViewById(R.id.User_Call);//电话
        L_Login = (Button) view.findViewById(R.id.L_Login);//退出登录


    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(getActivity(), "个人信息获取失败", Toast.LENGTH_SHORT).show();
                    break;
                case 1:

                    User_Balance.setText("0");//余额
                    tvUserName.setText(MyApplication.app.getUserNumber());//用户名
                    User_Integral.setText(MyApplication.app.getPoint());//积分

//                    String pic = userdata.getPic();
//                    if (pic != null) {
//                        Picasso.with(getActivity()).load(userdata.getPic()).into(User_Image);
//                    }
                    break;
            }
        }
    };


    private void inidataFromWeb() {
        String url = Contents.USER + MyApplication.app.getUserId();
        Request request = new Request.Builder().url(url).build();
        Contents.okhttp.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //失败
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String request = response.body().string();
                userdata = ParseUserData.getUser(request);

                //将数据绑定到变量上面
                String point = userdata.getPoint(); //积分
                String name = userdata.getUsername();//姓名
                String phone = userdata.getPhone();//手机号
                //将数据保存到全局
                MyApplication.app.setPoint(point);
                MyApplication.app.setUsername(name);
                MyApplication.app.setPhone(phone);
                //持久化保存数据
                MyApplication.app.saveUserData();

                handler.sendEmptyMessage(1);
            }
        });
    }


    //登陆
    private static final int REQUEST_CODE_LOGIN_USER = 1;

    @Override
    public void onClick(View v) {

        String userId = MyApplication.app.getUserId();

        switch (v.getId()) {

            case R.id.User_Setting://设置

                startActivity(new Intent(getActivity(), SystemSetActivity.class));
                break;

            case R.id.User_Image://登陆     如果已登陆不再去登陆

                if (userId == null) {
                    Intent intent = new Intent(getActivity(), LogInActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_LOGIN_USER);
                }
                break;

            case R.id.User_Order://礼品订单

                if (userId != null) {
                    startActivity(new Intent(getActivity(), GiftOrderActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), LogInActivity.class));
                }
                break;

            case R.id.Uesr_Current_integration://当前积分

                if (userId != null) {
                    startActivity(new Intent(getActivity(), IntegralActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), LogInActivity.class));
                }

                break;

            case R.id.Uesr_Modify_login_password://修改登陆密码

                if (userId != null) {
                    startActivity(new Intent(getActivity(), ModifyLoginPasswordActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), LogInActivity.class));
                }

                break;


            case R.id.Uesr_Pay_attention_to_the_store://关注的店家


                if (userId != null) {
                    startActivity(new Intent(getActivity(), AttentionShopActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), LogInActivity.class));
                }

                break;

            case R.id.Uesr_Receipt_address_management://地址管理

                if (userId != null) {
                    startActivity(new Intent(getActivity(), ShippingAddressActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), LogInActivity.class));
                }

                break;


            case R.id.Uesr_Share://分享好友


                break;

            case R.id.User_Call://客服电话

                callPhone();

                break;

            case R.id.L_Login://退出

                quitLogIn();
                Toast.makeText(getActivity(), "您已成功退出账号", Toast.LENGTH_SHORT).show();
                break;

        }
    }


    /**
     * 拨打客服
     */
    private void callPhone() {
        Intent callPhone = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + 8820666));
        callPhone.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(callPhone);
    }



    /**
     * 退出登录
     */
    private void quitLogIn() {
        MyApplication.app.setUserId(null);
        MyApplication.app.setUserNumber(null);
        MyApplication.app.setPoint(null);
        MyApplication.app.setUsername(null);
        MyApplication.app.saveUserData();

        //更新用户名
        tvUserName.setText("登录/注册");
        User_Image.setImageResource(R.mipmap.user);
        User_Integral.setText("");
        User_Balance.setText("");
        L_Login.setVisibility(View.GONE);
    }


    /**
     * 反向传值需要重写   onActivityResult()方法
     *
     * @param requestCode 请求码
     * @param resultCode  结果码
     * @param data        数据
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_LOGIN_USER:
                if (resultCode == Activity.RESULT_OK) {//登录成功
                    //更新用户名
                    inidataFromWeb();
                    L_Login.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    /**
     * Created by Administrator on 2016/11/5.
     */

    public static class OrdelAllUtils {

        public static List<OrderAll> getOrderAll(String json) {
            List<OrderAll> list = new ArrayList<>();

            try {
                JSONObject jsonObject = new JSONObject(json);
                JSONArray array = jsonObject.getJSONArray("orderlist");

                if (array.length() > 0 && null != array) {

                    for (int i = 0; i < array.length(); i++) {

                        list.add(JSON.parseObject(array.get(i).toString(),
                                OrderAll.class));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


            return list;
        }
    }
}
